/**
 * 脑电设备WebSocket客户端类
 * 负责设备连接、数据接收和会话管理
 */
class BrainWaveClient {
  constructor() {
    this.sessionId = null;
    this.websocket = null;
    this.isConnected = false;
    this.isRecording = false;
    this.baseUrl = 'http://localhost:8000';
    this.wsUrl = 'ws://localhost:8000';
    
    // 事件回调函数
    this.onBrainData = null;
    this.onBrainState = null;
    this.onError = null;
    this.onConnectionChange = null;
    this.onRecordingChange = null;
    
    // 重连配置
    this.reconnectAttempts = 0;
    this.maxReconnectAttempts = 5;
    this.reconnectDelay = 3000;
  }
  
  /**
   * 连接脑电设备
   * @param {string} port - 设备端口，可选
   * @returns {Promise<boolean>} 连接是否成功
   */
  async connect(port = null) {
    try {
      const response = await fetch(`${this.baseUrl}/api/device/connect`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ port })
      });
      
      const result = await response.json();
      console.log('API响应:', result); // 调试日志
      
      if (result.success) {
        // 兼容不同的响应格式
        this.sessionId = result.data?.session_id || result.session_id;
        
        if (!this.sessionId) {
          console.error('响应中缺少session_id');
          this.onError?.({ code: 'MISSING_SESSION_ID', message: '响应中缺少会话ID' });
          return false;
        }
        
        this.isConnected = true;
        this.onConnectionChange?.(true);
        
        // 建立WebSocket连接
        this.connectWebSocket();
        
        console.log('设备连接成功，会话ID:', this.sessionId);
        return true;
      } else {
        console.error('设备连接失败:', result.error?.message || result.message);
        this.onError?.(result.error || { code: 'CONNECTION_FAILED', message: result.message || '连接失败' });
        return false;
      }
    } catch (error) {
      console.error('连接请求失败:', error);
      this.onError?.({ code: 'CONNECTION_FAILED', message: '连接请求失败' });
      return false;
    }
  }
  
  /**
   * 建立WebSocket连接
   */
  connectWebSocket() {
    if (!this.sessionId) {
      console.error('无效的会话ID');
      return;
    }
    
    try {
      this.websocket = new WebSocket(`${this.wsUrl}/ws/brain_state/${this.sessionId}`);
      
      this.websocket.onopen = (event) => {
        console.log('WebSocket连接已建立');
        this.reconnectAttempts = 0;
      };
      
      this.websocket.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          this.handleMessage(message);
        } catch (error) {
          console.error('解析WebSocket消息失败:', error);
        }
      };
      
      this.websocket.onclose = (event) => {
        console.log('WebSocket连接已关闭');
        if (this.isConnected && this.reconnectAttempts < this.maxReconnectAttempts) {
          this.attemptReconnect();
        }
      };
      
      this.websocket.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.onError?.({ code: 'WEBSOCKET_ERROR', message: 'WebSocket连接错误' });
      };
    } catch (error) {
      console.error('创建WebSocket连接失败:', error);
      this.onError?.({ code: 'WEBSOCKET_CREATE_FAILED', message: '创建WebSocket连接失败' });
    }
  }
  
  /**
   * 尝试重连WebSocket
   */
  attemptReconnect() {
    this.reconnectAttempts++;
    console.log(`尝试重连WebSocket (${this.reconnectAttempts}/${this.maxReconnectAttempts})`);
    
    setTimeout(() => {
      if (this.isConnected) {
        this.connectWebSocket();
      }
    }, this.reconnectDelay);
  }
  
  /**
   * 处理WebSocket消息
   * @param {Object} message - 接收到的消息
   */
  handleMessage(message) {
    console.log('handleMessage: 收到消息:', message);
    console.log('onBrainData回调函数:', typeof this.onBrainData);
    console.log('onBrainState回调函数:', typeof this.onBrainState);
    
    // 根据消息内容判断消息类型
    if (message.type) {
      // 有明确type字段的消息
      switch (message.type) {
        case 'brain_data':
          // 脑电数据消息
          console.log('调用onBrainData回调，数据:', message.data);
          this.onBrainData?.(message.data);
          break;
          
        case 'brain_state':
          // 脑状态分析消息
          console.log('调用onBrainState回调，数据:', message.data);
          this.onBrainState?.(message.data);
          break;
          
        case 'error':
          // 错误消息
          console.error('WebSocket错误消息:', message.error);
          this.onError?.(message.error);
          break;
          
        default:
          console.warn('未知的消息类型:', message.type, '完整消息:', message);
      }
    } else if (message.state && message.confidence !== undefined) {
      // 包含state和confidence的消息，作为脑状态分析消息处理
      console.log('处理脑状态分析消息:', message);
      console.log('调用onBrainState回调');
      this.onBrainState?.(message);
      
      // 如果消息还包含average_ratios，也作为脑电数据处理
      if (message.details && message.details.average_ratios) {
        console.log('同时处理脑电波段数据:', message);
        console.log('调用onBrainData回调');
        this.onBrainData?.(message);
      }
    } else if (message.brain_state) {
      // 包含brain_state的消息，直接作为脑状态分析消息处理
      console.log('处理脑状态分析消息:', message.brain_state);
      this.onBrainState?.(message);
      
      // 如果brain_state消息包含details.average_ratios，也作为脑电数据处理
      if (message.brain_state.details && message.brain_state.details.average_ratios) {
        console.log('从brain_state消息中提取脑电波段数据:', message.brain_state.details.average_ratios);
        console.log('调用onBrainData回调');
        // 构造适合BrainWaveChart的数据格式
        const brainData = {
          details: {
            average_ratios: message.brain_state.details.average_ratios
          }
        };
        this.onBrainData?.(brainData);
      }
    } else if (message.brain_data || message.eeg_data) {
      // 包含脑电数据的消息
      console.log('处理脑电数据消息:', message);
      this.onBrainData?.(message);
    } else if (message.details && message.details.average_ratios) {
      // 仅包含average_ratios的消息，作为脑电数据处理
      console.log('处理脑电波段数据:', message);
      this.onBrainData?.(message);
    } else {
      console.warn('无法识别的消息格式:', message);
    }
  }
  
  /**
   * 开始记录脑电数据
   * @returns {Promise<boolean>} 是否成功开始记录
   */
  async startRecording() {
    if (!this.sessionId) {
      console.error('设备未连接');
      return false;
    }else{
      console.log('设备已连接');
    }
    console.log('startRecording: 开始录制请求，sessionId:', this.sessionId);
    try {
      const response = await fetch(`${this.baseUrl}/api/recording/start/${this.sessionId}`, {
        method: 'POST'
      });
      
      const result = await response.json();
      console.log('startRecording: API响应:', result);
      
      // 检查不同的响应格式
      if (result.success || (result && result.session_id)) {
        this.isRecording = true;
        this.onRecordingChange?.(true);
        console.log('开始记录脑电数据');
        return true;
      } else {
        console.error('开始记录失败:', result.error?.message || result.message || '未知错误');
        this.onError?.(result.error || { message: result.message || '开始记录失败' });
        return false;
      }
    } catch (error) {
      console.error('开始记录请求失败:', error);
      this.onError?.({ code: 'START_RECORDING_FAILED', message: '开始记录请求失败' });
      return false;
    }
  }
  
  /**
   * 停止记录脑电数据
   * @returns {Promise<boolean>} 是否成功停止记录
   */
  async stopRecording() {
    if (!this.sessionId) {
      console.error('设备未连接');
      return { success: false, message: '设备未连接' };
    }
    
    try {
      const response = await fetch(`${this.baseUrl}/api/recording/stop/${this.sessionId}`, {
        method: 'POST'
      });
      
      const result = await response.json();
      console.log('stopRecording: API响应:', result);
      
      if (result.success) {
        this.isRecording = false;
        this.onRecordingChange?.(false);
        console.log('停止记录脑电数据');
        return { success: true };
      } else {
        console.error('停止记录失败:', result.error?.message || result.message);
        this.onError?.(result.error);
        return { success: false, message: result.error?.message || result.message || '停止记录失败' };
      }
    } catch (error) {
      console.error('停止记录请求失败:', error);
      this.onError?.({ code: 'STOP_RECORDING_FAILED', message: '停止记录请求失败' });
      return { success: false, message: '停止记录请求失败' };
    }
  }
  
  /**
   * 获取设备状态
   * @returns {Promise<Object|null>} 设备状态信息
   */
  async getDeviceStatus() {
    if (!this.sessionId) {
      console.log('getDeviceStatus: 没有sessionId');
      return null;
    }
    
    try {
      const response = await fetch(`${this.baseUrl}/api/device/status/${this.sessionId}`);
      const result = await response.json();
      // console.log('getDeviceStatus: API响应:', result);
      
      // 检查响应是否包含必要的状态字段
      if (result && (result.session_id || result.is_connected !== undefined)) {
        // console.log('getDeviceStatus: 返回数据:', result);
        return result;
      } else if (result.success) {
        // console.log('getDeviceStatus: 返回数据:', result.data);
        return result.data;
      } else {
        console.error('获取设备状态失败:', result.error?.message || '未知错误');
        return null;
      }
    } catch (error) {
      console.error('获取设备状态请求失败:', error);
      return null;
    }
  }
  
  /**
   * 更新分析参数
   * @param {Object} params - 分析参数
   * @returns {Promise<boolean>} 是否成功更新
   */
  async updateAnalysisParams(params) {
    if (!this.sessionId) {
      console.error('设备未连接');
      return false;
    }
    
    try {
      const response = await fetch(`${this.baseUrl}/api/analysis/params/${this.sessionId}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(params)
      });
      
      const result = await response.json();
      if (result.success) {
        console.log('分析参数更新成功');
        return true;
      } else {
        console.error('更新分析参数失败:', result.error?.message);
        this.onError?.(result.error);
        return false;
      }
    } catch (error) {
      console.error('更新分析参数请求失败:', error);
      this.onError?.({ code: 'UPDATE_PARAMS_FAILED', message: '更新分析参数请求失败' });
      return false;
    }
  }
  
  /**
   * 断开设备连接
   * @returns {Promise<void>}
   */
  async disconnect() {
    if (!this.sessionId) {
      return;
    }
    
    try {
      // 关闭WebSocket连接
      if (this.websocket) {
        this.websocket.close();
        this.websocket = null;
      }
      
      // 断开设备连接
      await fetch(`${this.baseUrl}/api/device/disconnect/${this.sessionId}`, {
        method: 'POST'
      });
      
      console.log('设备连接已断开');
    } catch (error) {
      console.error('断开连接失败:', error);
    } finally {
      this.sessionId = null;
      this.isConnected = false;
      this.isRecording = false;
      this.reconnectAttempts = 0;
      
      this.onConnectionChange?.(false);
      this.onRecordingChange?.(false);
    }
  }
  
  /**
   * 获取连接状态
   * @returns {boolean} 是否已连接
   */
  getConnectionStatus() {
    return this.isConnected;
  }
  
  /**
   * 获取记录状态
   * @returns {boolean} 是否正在记录
   */
  getRecordingStatus() {
    return this.isRecording;
  }
  
  /**
   * 获取会话ID
   * @returns {string|null} 会话ID
   */
  getSessionId() {
    return this.sessionId;
  }
}

export default BrainWaveClient;